<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Report extends MY_Controller {

	function Report() {
		parent::__construct();
		$this->load->model('report_model');
		$this->load->model('report_group_model');
		$this->load->model('report_item_model');
		$this->load->model('report_data_model');
		$this->load->model('realtime_data_model');
		$this->load->model('realtime_item_model');
		$this->load->model('user_model');
		$this->load->library('email');
	}

	public function index() {
		$realtime_servers = $this->realtime_item_model->get_server_list();
		$realtime_item_names = $this->realtime_item_model->get_all_item_name();
		$alarm_info = $this->realtime_data_model->check_alarm();

		$group_names_list  = $this->report_group_model->get_group_list();
		$report_names_list = $this->report_model->report_lists();
		$group_ids = $this->report_group_model->get_first_row(); 
		$group_id = $group_ids['group_id'];
		$data_date = date('Y-m-d');
		$data_arrays = $this->_get_report_datas($group_id, $data_date);
		$group_name = $this->report_group_model->get_group_by_id($group_id);
		$data_arrays['group_name'] = $group_name['group_name'];
		if($this->session->userdata('logged_in')){
			$this->load->view('dashboard', array('data_arrays' => $data_arrays, 'realtime_servers' =>$realtime_servers, 'realtime_item_names' =>$realtime_item_names, 'report_names_list' => $report_names_list, 'group_names_list' => $group_names_list));
		} else {
			$this->load->view('login');
		}
		
	}

	public function add() {
		$report_name  = $this->input->post('report_name');
		$report_email = $this->input->post('report_email');
		$reports      = $this->report_model->get_by_name($report_name);
		if (empty($reports)) {
			$this->report_model->add($report_name,$report_email);
		} else {
			echo "<script>alert('Already exist');window.history.go(-1);</script>";
		}
		redirect("/report/reports");
	}

	public function delete() {
		$report_id  = $this->input->get('report_id');
		$report_ids      = $this->report_model->get_by_id($report_id);
		if (!empty($report_ids)) {
			$this->report_model->delete($report_id);
		} else {
			echo "<script>alert('Not exist');window.history.go(-1);</script>";
		}
		redirect("/report/reports");
	}

	public function update() {
		$report_id    = $this->input->post('report_id');
		$report_name  = $this->input->post('report_name');
		$report_email = $this->input->post('report_email');
		
		$this->report_model->update($report_id, $report_name, $report_email);
		redirect("/report/reports");
	}

	public function reports() {
		$all_report = $this->report_model->report_lists();
		if($this->session->userdata('logged_in') && $this->session->userdata('role_id') == 1){
			$this->load->view('report', array('all_report' => $all_report));
		} else {
			$this->load->view('login');
		}
	}

	public function show_data() {
		$group_id = intval($this->input->post('group_id'));
		$group_names_list = $this->report_group_model->get_group_list();
		$report_names_list = $this->report_model->report_lists();
		$data_date = $this->input->post('data_date');
		// TODO check params
		if ($group_id == "") { 
			echo "<script>alert('Not select group');window.history.go(-1);</script>";;
		}
		if ($data_date !== date("Y-m-d", strtotime($data_date))) {
			echo "<script>alert('time format error');window.history.go(-1);</script>";
				
		}
		$data_arrays = $this->_get_report_datas($group_id, $data_date);
		echo json_encode($data_arrays);
		//if($this->session->userdata('logged_in')){
		//	$this->load->view('dashboard', array('data_arrays' => $data_arrays, 'report_names_list' => $report_names_list, 'group_names_list' => $group_names_list));
		//} else {
		//	$this->load->view('login');
		//}
	}

	public function history_data() { 
		$item_key = $this->input->get('item_key');
		$item_ids = $this->report_item_model->get_id_by_ikey($item_key);
		$last_month_datas    = $this->report_data_model->last_month_data($item_ids['item_id']);
		
		foreach ($last_month_datas as $value) {
			$datas['his_data'][] = array(
				'data_value' => $this->add_data_by_server($item_key, $value['data_date']),
				'data_date'  => $value['data_date']
			);
		}
		echo json_encode($datas);
	}

	public function add_data_by_server($item_key, $data_date) {
		$item_ids = $this->report_item_model->get_ids_by_ikey($item_key);
		$day_data = 0;
		foreach ($item_ids as $row) {
			$row_data = $this->report_data_model->get_by_id_and_date($row['item_id'], $data_date);
			$day_data +=$row_data['data_value'];
		}
		return $day_data;
	}

	public function _get_days($date) {
		$today     = date('Y-m-d', strtotime("$date"));
		$yesterday = date('Y-m-d', strtotime('-1 day', strtotime("$date")));
		$lastweek  = date('Y-m-d', strtotime('-7 day', strtotime("$date")));
		$lastmonth = date('Y-m-d', strtotime('last month', strtotime("$date")));
		return array(
			$today,
			$yesterday,
			$lastweek,
			$lastmonth,
		);
	}

	//send email
	public function send_email() {
		$report_id = $this->input->get('report_id');
		$data_date = $this->input->get('data_date');
		if (!is_numeric($report_id)) {
			echo "<script>alert('This report_id isn't in the table');window.history.go(-1);</script>";
			
		}
		if ($data_date !== date('Y-m-d', strtotime($data_date))) {
			$data_date = date('Y-m-d');
		}
		$report = $this->report_model->get_by_id($report_id);
		$group_ids = $this->report_group_model->get_group_id($report_id);
		$tables = "";
		foreach ($group_ids as $row) {
			$tables.= $this->_generate_table($row['group_id'], $data_date);
		}

		// generate report
		$head = "<head><meta chaset='utf-8'><title>Report Data</title><style>table{font-family: verdana,arial,sans-serif;font-size:11px;color:#333333;border-width: 1px;border-color: #a9c6c9;
				border-collapse: collapse;}table caption{font-size:16px;line-height:28px;text-align:left;font-weight:bold;}
				table th {border-width: 1px;padding: 8px;border-style: solid;border-color: #a9c6c9;background-color: #c3dde0;}
				table td:first-child{background-color: #d4e3e5;}
				table td {border-width: 1px;padding: 8px;border-style: solid;border-color: #a9c6c9;background-color: #ffffff;}</style></head><body>";
		$foot = "</body></html>";
		$content = $head.$tables.$foot;
		echo $content;

		$this->load->library('mailer');
		$this->mailer->sendmail($report['report_email'], "[{$data_date}]{$report['report_name']}", $content);
		
	}

	private function _generate_table($group_id, $data_date) {
		$report = $this->_get_report_datas($group_id, $data_date);
		$table = "<table><caption>{$report['group_name']}</caption><thead><tr><th>Item Name</th><th>Today</th><th>Yesterday</th><th>Daily change</th><th>Last Week</th><th>Weekly Change</th><th>Last Month</th>
				<th>Monthly Change</th></tr></thead><tbody>";
		foreach ($report['report_datas'] as $item) {
			$item_name      = $item['item_name'];
			$today_data     = $item['today_data'];
			$yesterday_data = $item['yesterday_data'];
			$yesterday_rate = $item['yesterday_rate'];
			$lastweek_data  = $item['lastweek_data'];
			$lastweek_rate  = $item['lastweek_rate'];
			$lastmonth_data = $item['lastmonth_data'];
			$lastmonth_rate = $item['lastmonth_rate'];
			$table = $table."<tr><td>$item_name</td><td>$today_data</td><td>$yesterday_data</td><td>$yesterday_rate</td><td>$lastweek_data</td><td>$lastweek_rate</td>
				  <td>$lastmonth_data</td><td>$lastmonth_rate</td></tr>";
		}
		$table = $table."</tbody></table><br/>";
		return $table;
	}

	private function _get_report_datas($group_id, $data_date) {
		$dates = $this->_get_days($data_date);
		// find all items
		$items = $this->report_item_model->get_diff_items($group_id);
		$report = $this->report_group_model->get_group_by_id($group_id);
		$report['data_date'] = $dates[0];
		$report['report_datas'] = array();
		foreach ($items as $item) {
			// find several days' data of items
			// $datas = $this->report_data_model->get_list_by_dates($item['item_id'], $dates);
			$datas_today     = $this->add_data_by_server($item['item_key'], $dates[0]);
			$datas_yesterday = $this->add_data_by_server($item['item_key'], $dates[1]);
			$datas_lastweek  = $this->add_data_by_server($item['item_key'], $dates[2]);
			$datas_lastmonth = $this->add_data_by_server($item['item_key'], $dates[3]);
			
			$today_data     = $this->_get_data($datas_today);
			$yesterday_data = $this->_get_data($datas_yesterday);
			$lastweek_data  = $this->_get_data($datas_lastweek);
			$lastmonth_data = $this->_get_data($datas_lastmonth);
			$yesterday_rate = $this->_get_persent($today_data, $yesterday_data);
			$lastweek_rate  = $this->_get_persent($today_data, $lastweek_data);
			$lastmonth_rate = $this->_get_persent($today_data, $lastmonth_data);

			$report['report_datas'][] = array(
				'item_name'      => $item['item_name'],
				'item_key'      => $item['item_key'],
				'today_data'     => $today_data, 
				'yesterday_data' => $yesterday_data,
				'yesterday_rate' => $yesterday_rate,
				'lastweek_data'  => $lastweek_data,
				'lastweek_rate'  => $lastweek_rate,
				'lastmonth_data' => $lastmonth_data,
				'lastmonth_rate' => $lastmonth_rate
			);
		}

		return $report;
	}

	private function _get_data($data) {
		if (isset($data)) {
			return $data;
		}
		return 'no data';
	}

	private function _get_persent($divisor, $dividend) {
		if (intval($dividend) != 0 && is_numeric($divisor)) {
			$font = $divisor >= $dividend ? '<font color="red">' : '<font color="green">';
			return $font . round(($divisor - $dividend) / $dividend * 100, 2) . '%</font>';
		}
		return 'no data';
	}
} 